<!-- 主布局组件 -->
<template>
  <div class="min-h-screen bg-gray-50 flex">
    <!-- 左侧导航栏 -->
    <div
      :class="[
        'bg-white shadow-md flex flex-col transition-all duration-300 h-screen fixed left-0 top-0 z-10',
        isCollapsed ? 'w-16' : 'w-56',
      ]"
    >
      <!-- 顶部Logo和折叠按钮 -->
      <div :class="[
        'py-4 px-4 border-b',
        isCollapsed ? 'flex flex-col items-center space-y-3' : 'flex items-center justify-between'
      ]">
        <div class="flex items-center">
          <img
            src="../assets/logo.png"
            alt="Logo"
            class="w-8 h-8"
          />
          <span v-if="!isCollapsed" class="ml-2 font-bold text-gray-700">Eon Mind</span>
        </div>
        <button @click="toggleCollapse" class="collapse-btn">
          <MenuFoldOutlined v-if="!isCollapsed" />
          <MenuUnfoldOutlined v-if="isCollapsed" />
        </button>
      </div>

      <div class="flex-1 overflow-y-auto">
        <a-menu
          v-model:openKeys="openKeys"
          v-model:selectedKeys="selectedKeys"
          mode="inline"
          :items="menuItems"
          :inline-collapsed="isCollapsed"
          @click="handleMenuClick"
          class="custom-menu"
        />
      </div>

      <!-- 退出登录按钮 -->
      <div class="border-t border-gray-200 py-4 px-2 mt-4">
        <div
          class="flex items-center py-2 px-3 rounded-lg text-red-600 hover:bg-red-50 cursor-pointer"
          @click="handleLogout"
        >
          <LogoutOutlined />
          <span class="ml-3" v-if="!isCollapsed">退出登录</span>
        </div>
      </div>
    </div>
    <div :class="['flex-1', isCollapsed ? 'ml-16' : 'ml-56']">
      <router-view></router-view>
    </div>
  </div>
</template>

<script setup>
import { ref, watch, onMounted, h } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import {
  UserOutlined,
  LockOutlined,
  SettingOutlined,
  MessageOutlined,
  PictureOutlined,
  VideoCameraOutlined,
  CrownOutlined,
  GiftOutlined,
  ShoppingCartOutlined,
  FileTextOutlined,
  BookOutlined,
  UploadOutlined,
  MenuFoldOutlined,
  MenuUnfoldOutlined,
  LogoutOutlined,
} from '@ant-design/icons-vue'
import { clearUserInfo } from '../utils/auth'
import { ElMessageBox, ElMessage } from 'element-plus'

const router = useRouter()
const route = useRoute()
const isCollapsed = ref(false)
const selectedKeys = ref([])
const openKeys = ref([])

// 菜单项生成函数
function getItem(label, key, icon, children, type) {
  return {
    key,
    icon,
    children,
    label,
    type,
  }
}

// 菜单项配置
const menuItems = [
  getItem('用户服务', 'user', () => h(UserOutlined), [
    getItem('用户中心', '/', () => h(UserOutlined)),
    getItem('安全设置', '/security-settings', () => h(LockOutlined)),
    getItem('通知管理', '/notification-settings', () => h(SettingOutlined)),
  ]),
  getItem('AI 服务', 'ai', () => h(MessageOutlined), [
    getItem('AI 对话', '/ai-chat', () => h(MessageOutlined)),
    getItem('AI 绘图', '/ai-drawing', () => h(PictureOutlined)),
    getItem('AI 视频', '/ai-video', () => h(VideoCameraOutlined)),
  ]),
  getItem('会员服务', 'member', () => h(CrownOutlined), [
    getItem('会员中心', '/member-center', () => h(CrownOutlined)),
    getItem('积分管理', '/points-management', () => h(GiftOutlined)),
  ]),
  getItem('订单服务', 'order', () => h(ShoppingCartOutlined), [
    getItem('商城', '/product-display', () => h(ShoppingCartOutlined)),
    getItem('订单管理', '/order', () => h(FileTextOutlined)),
  ]),
  getItem('知识库', 'knowledge', () => h(BookOutlined), [
    getItem('我的知识库', '/knowledge-base-management', () => h(BookOutlined)),
    getItem('文档上传', '/document-upload', () => h(UploadOutlined)),
  ]),
]

// 切换菜单折叠状态
const toggleCollapse = () => {
  isCollapsed.value = !isCollapsed.value
  localStorage.setItem('sidebarCollapsed', isCollapsed.value ? 'true' : 'false')
}

// 从本地存储中恢复折叠状态
const initCollapsedState = () => {
  const savedState = localStorage.getItem('sidebarCollapsed')
  if (savedState) {
    isCollapsed.value = savedState === 'true'
  } else {
    // 默认不折叠，确保文字显示
    isCollapsed.value = false
  }
}

// 处理菜单点击
const handleMenuClick = (e) => {
  // 只有当点击的是叶子节点（有实际路由的菜单项）时才进行路由跳转
  if (e.key.startsWith('/')) {
    router.push(e.key)
  }
}

// 监听路由变化，更新选中的菜单项
watch(
  () => route.path,
  (path) => {
    selectedKeys.value = [path]
    // 找到当前路径对应的父级菜单
    const parentKey = menuItems.find((item) =>
      item.children?.some((child) => child.key === path)
    )?.key
    if (parentKey) {
      openKeys.value = [parentKey]
    }
  },
  { immediate: true }
)

// 初始化
onMounted(() => {
  initCollapsedState()
})

// 处理退出登录
const handleLogout = () => {
  ElMessageBox.confirm('确定要退出登录吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      clearUserInfo()
      ElMessage.success('退出登录成功')
      router.push('/login')
    })
    .catch(() => {
      // 取消退出
    })
}
</script>

<style scoped>
/* 添加过渡效果 */
.transition-all {
  transition-property: all;
  transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
  transition-duration: 300ms;
}

/* 确保宽度设置正确 */
.w-16 {
  width: 4rem;
}

.w-56 {
  width: 14rem;
}

/* 自定义菜单样式 */
.custom-menu {
  border: none !important;
  background: transparent !important;
}

/* 确保菜单项文字显示 */
:deep(.ant-menu-item) {
  display: flex !important;
  align-items: center !important;
}

:deep(.ant-menu-submenu-title) {
  display: flex !important;
  align-items: center !important;
}

/* 优化的折叠按钮样式 */
.collapse-btn {
  width: 32px;
  height: 32px;
  border-radius: 6px;
  background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
  border: 1px solid #e2e8f0;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  color: #64748b;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  position: relative;
  overflow: hidden;
}

.collapse-btn::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(135deg, rgba(59, 130, 246, 0.1) 0%, rgba(147, 197, 253, 0.1) 100%);
  opacity: 0;
  transition: opacity 0.3s ease;
}

.collapse-btn:hover {
  background: linear-gradient(135deg, #eff6ff 0%, #dbeafe 100%);
  border-color: #3b82f6;
  color: #3b82f6;
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(59, 130, 246, 0.15);
}

.collapse-btn:hover::before {
  opacity: 1;
}

.collapse-btn:active {
  transform: translateY(0);
  box-shadow: 0 2px 6px rgba(59, 130, 246, 0.2);
}

.collapse-btn .el-icon {
  font-size: 16px;
  transition: transform 0.3s ease;
  position: relative;
  z-index: 1;
}

.collapse-btn:hover .el-icon {
  transform: scale(1.1);
}
</style>
